import pandas as pd
import flet as ft
from flet import View, AppBar, Text, ElevatedButton, colors, Page, Icon, Card, Container, Column, Row, padding, \
    ListTile, ListView, Checkbox, TextField, FloatingActionButton, icons
from flet_core import TemplateRoute


class App(object):
    def __init__(self, page: ft.Page):
        self.page_route = []
        self.data = self.read_file()
        self.page = page
        self.main()

    def read_file(self):
        path = '数据.xlsx'
        df = pd.read_excel(path)
        # 根据df中的某一列排序
        df = df.sort_values(by='音标')
        return df

    def view_pop(self, e):
        print("View pop:", e.view)
        self.page.views.pop()
        top_view = self.page.views[-1]
        self.page.go(top_view.route)

    def route_change(self, e):
        print("Route change:", e.route)
        self.page.views.clear()
        self.page.views.append(self.root_view())
        troute = TemplateRoute(e.route)
        if troute.match("/col_view/:title"):
            self.page.views.append(self.iloc_view(troute.title))
        elif troute.match("/data_view/:title/:col"):
            self.page.views.append(self.data_view(troute.title, troute.col))
        self.page.update()

    def root_view(self):
        return View(
            "/",
            [
                AppBar(title=Text("三价动词谓语句定语和状语对应语义角色信息查询系统"), bgcolor=colors.SURFACE_VARIANT),
                ft.Text("提示：请选择要查询的三价动词"),
                self.list_title(),
            ],
        )

    def list_title(self):
        card = ft.Card(height=500)
        list_view = ft.ListView(expand=True, spacing=10)
        group_data = self.data.groupby('音标')
        group_data = group_data.groups.keys()
        for i in group_data:
            list_view.controls.append(
                ft.ListTile(
                    title=ft.Text(f"{i}"),
                    on_click=self.list_title_click,
                    data=i
                )
            )
        card.content = ft.Container(width=500, content=list_view, padding=ft.padding.symmetric(vertical=10))
        return card

    def list_title_click(self, e):
        self.page.go(f"/col_view/{e.control.data}")

    def iloc_view(self, title):
        return View(
            "/col_view",
            [
                AppBar(title=Text("请选择查询的属性"), bgcolor=colors.SURFACE_VARIANT),
                self.iloc_data(title)
            ],
        )

    def iloc_data(self, title):
        print(title)
        gv = ft.GridView(expand=True, max_extent=150, child_aspect_ratio=1)
        col_list = self.data.columns.tolist()
        for col in col_list:
            gv.controls.append(
                ft.Container(
                    ft.Text(f"{col}"),
                    alignment=ft.alignment.center,
                    bgcolor=ft.colors.AMBER_100,
                    border=ft.border.all(1, ft.colors.AMBER_400),
                    border_radius=ft.border_radius.all(5),
                    data={"title": title, "col": col},
                    on_click=self.iloc_data_click,
                )
            )
        return gv

    def iloc_data_click(self, e):
        title = e.control.data["title"]
        col = e.control.data["col"]
        self.page.go(f"/data_view/{title}/{col}")

    def data_view(self, title, col):
        print(title, col)
        result = self.data[self.data["音标"] == title].copy()
        print(result)
        data_list = result[col]
        print(data_list)
        card = ft.Card(height=500)
        list_view = ft.ListView(expand=True, spacing=10)
        for i in data_list:
            list_view.controls.append(
                ft.ListTile(
                    title=ft.Text(f"{i}"),
                    # on_click=self.list_title_click,
                )
            )
        card.content = ft.Container(width=500, content=list_view, padding=ft.padding.symmetric(vertical=10))
        return View(
            "/data_view",
            [
                AppBar(
                    title=Text("返回首页"), bgcolor=colors.SURFACE_VARIANT
                ),
                card,
                ElevatedButton("返回上一页", on_click=lambda e: self.page.go(f"/col_view/{title}")),
            ],
        )

    def main(self):
        self.page.title = "查询系统"
        self.page.horizontal_alignment = ft.CrossAxisAlignment.CENTER
        self.page.auto_scroll = True
        self.page.update()
        self.page.on_route_change = self.route_change
        self.page.on_view_pop = self.view_pop
        self.page.go(self.page.route)
        # home = Trivalent()
        # self.page.add(home)


if __name__ == '__main__':
    ft.app(target=App)
    # ft.Page()
